﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using LaunchPad.Core.Maths;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Xml.Serialization;

namespace LaunchPad.Core
{
    public class ProductCharacterization : INotifyPropertyChanged
    {
        public ProductCharacterization()
        {
            Samples = new ObservableCollection<ProductCharacterizationSample>();
            Samples.CollectionChanged += Samples_CollectionChanged;
        }

        void Samples_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems != null)
            {
                foreach(ProductCharacterizationSample sample in e.NewItems)
                    sample.PropertyChanged += sample_PropertyChanged;
            }

            if (e.OldItems != null)
            {
                foreach (ProductCharacterizationSample sample in e.OldItems)
                    sample.PropertyChanged -= sample_PropertyChanged;
            }

            OnPropertyChanged("AverageAdjustedApex");
            OnPropertyChanged("AnySamples");
        }

        void sample_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            OnPropertyChanged("AverageAdjustedApex");
        }

        public ObservableCollection<ProductCharacterizationSample> Samples { get; set; }

        [XmlIgnore]
        public TimeSpan AverageAdjustedApex
        {
            get
            {
                if (!AnySamples)
                    return TimeSpan.Zero;

                var aveMs = Samples.Average(sample => sample.AdjustedApex.TotalMilliseconds);
                return TimeSpan.FromMilliseconds(aveMs);
            }
        }

        [XmlIgnore]
        public bool AnySamples
        {
            get { return Samples.Any(); }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string property)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }
}
